/**************************************************************************************
 *
 * @(#) SecurityFilter.java
 * @Package com.jgdt.jgdtkasannong_university_gene_backend.common.example
 **************************************************************************************/
package com.jgdt.jgdtkasannong_university_gene_backend.common.example;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @description: 捕获Security自定义抛出异常信息
 * @author: huangAn
 * @createDate: 2025/04/18
 */
public class SecurityFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException {
        try {
            chain.doFilter(req, res);
        } catch (AuthenticationException ex) {
            req.setAttribute("authException", ex);  // 传递异常到控制器层
            res.setStatus(HttpStatus.UNAUTHORIZED.value());
        }
    }
}




